package xyj.sparrow.client.listener;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;
import lombok.extern.slf4j.Slf4j;
import xyj.sparrow.client.NettyClient;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ConnectListener implements ChannelFutureListener {
    private final NettyClient nettyClient;

    public ConnectListener(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    @Override
    public void operationComplete(ChannelFuture future) {
        if (!future.isSuccess()) {
            log.info("尝试连接");
            final EventLoop eventLoop = future.channel().eventLoop();
            eventLoop.schedule(nettyClient::connect, 1L, TimeUnit.SECONDS);
        } else {
            log.info("连接成功");
            nettyClient.setChannel(future.channel());
            nettyClient.getIsActive().compareAndSet(false, true);
        }
    }
}
